package com.coffee.web.utils;

import com.alibaba.fastjson.JSONObject;
import com.coffee.core.enums.ExceptionEnum;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.util.HttpClientUtil;
import com.coffee.order.api.sku.result.PayOrderResult;
import com.coffee.order.api.utils.MessageUtil;
import com.coffee.order.api.utils.RandomHelper;
import com.coffee.order.api.utils.UnifiedOrder;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * xiayao
 * 2021/7/19
 */
@Slf4j
@Component
public class WeixinAppletsUtil {


    public static String appId;

    public static String newAppId;

    public static String mchId;

    public static String signKey;

    @Value("${parameter.weixin.appId}")
    private void setAppId(String appIdStr) {
        appId = appIdStr;
    }

    @Value("${parameter.weixin.newAppId}")
    private void setNewAppId(String newAppIdStr) {
        newAppId = newAppIdStr;
    }

    @Value("${parameter.weixin.mchId}")
    private void setMchId(String mchIdStr) {
        mchId = mchIdStr;
    }

    @Value("${parameter.weixin.signKey}")
    private void setSignKey(String signKeyStr) {
        signKey = signKeyStr;
    }


    public static Map<String, String> wechatAppletsPay(PayOrderResult payOrder, String userIp, String openId, String notifyUrl, String outTradeNo) throws BusinessException {
        // step 2:去微信那边调用统一下单接口
        String body = payOrder.getTitle();
        String nonceStr = RandomHelper.getNonceStr();
        String tradeType = "JSAPI";
        String weixinSignKey = signKey;

        Integer totalFee = new BigDecimal("" + payOrder.getMoney()).multiply(new BigDecimal("100")).intValue();

        SortedMap<String, String> parameters = new TreeMap<String, String>();
        if (payOrder.getAppletType() == 1) {
            parameters.put("appid", appId);
        } else {
            parameters.put("appid", newAppId);
        }
        parameters.put("mch_id", mchId);
        parameters.put("nonce_str", nonceStr);
        parameters.put("body", body);
        parameters.put("out_trade_no", outTradeNo);
        parameters.put("total_fee", totalFee + "");
        parameters.put("spbill_create_ip", userIp);
        parameters.put("notify_url", notifyUrl);
        parameters.put("trade_type", tradeType);
        parameters.put("openid", openId);
        String characterEncoding = "UTF-8";
        String mySign = WeixinSignHelper.createSign(characterEncoding, parameters, weixinSignKey);

        UnifiedOrder order = new UnifiedOrder();
        if (payOrder.getAppletType() == 1) {
            order.setAppid(appId);
        } else {
            order.setAppid(newAppId);
        }
        order.setMch_id(mchId);
        order.setNonce_str(nonceStr);
        order.setSign(mySign);
        order.setBody(body);
        order.setNotify_url(notifyUrl);
        order.setOut_trade_no(outTradeNo);
        order.setTotal_fee(totalFee);
        order.setTrade_type(tradeType);
        order.setSpbill_create_ip(userIp);
        order.setOpenid(openId);
        log.info("===去微信小程序那下订单：客户订单号:" + outTradeNo + ",notifyUrl=" + notifyUrl + ",order===" + JSONObject.toJSONString(order));
        long begin = System.currentTimeMillis();
        try {
            String ret = HttpClientUtil.postBody("https://api.mch.weixin.qq.com/pay/unifiedorder", order.toXml());
            long end = System.currentTimeMillis();
            log.info("去微信小程序支付=" + outTradeNo + "去微信小程序下订单花费时间：" + (end - begin));
            log.info(ret);
            // 下单成功后
            Map<String, String> retMap = MessageUtil.parseXml(ret);

            if ("SUCCESS".equals(retMap.get("return_code")) && "SUCCESS".equals(retMap.get("result_code"))) {
                // 统一下单成功
                String prepayId = retMap.get("prepay_id");
                SortedMap<String, String> model = new TreeMap<String, String>();
                if (payOrder.getAppletType() == 1) {
                    model.put("appId", appId);
                } else {
                    model.put("appId", newAppId);
                }
                model.put("timeStamp", new Date().getTime() / 1000 + "");
                model.put("nonceStr", RandomHelper.getNonceStr());
                model.put("package", "prepay_id=" + prepayId);
                model.put("signType", "MD5");
                String modelSign = WeixinSignHelper.createSign(characterEncoding, model, weixinSignKey);
                model.put("paySign", modelSign);

                Map<String, String> map = new HashMap<String, String>();
                map.put("timeStamp", model.get("timeStamp"));
                map.put("nonceStr", model.get("nonceStr"));
                map.put("package", model.get("package"));
                map.put("signType", model.get("signType"));
                map.put("paySign", model.get("paySign"));
                if (payOrder.getAppletType() == 1) {
                    map.put("appid", appId);
                } else {
                    map.put("appid", newAppId);
                }
                map.put("returnUrl", payOrder.getReturnUrl());
                return map;
            } else {
                log.error("=============统一下单失败==========" + JSONObject.toJSONString(retMap));
                throw new BusinessException(ExceptionEnum.ERROR_9999.getCode(), retMap.get("return_code") + "统一下单失败");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            throw new BusinessException(ExceptionEnum.ERROR_9999.getCode(), "ClientProtocolException");
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(ExceptionEnum.ERROR_9999.getCode(), "IOException");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ExceptionEnum.ERROR_9999.getCode(), "Exception");
        }
    }
}
